package com.yzy.common;

import com.yzy.pojo.JwtUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Objects;

/**
 * 处理token信息
 *
 * @author 杨志远
 * @date 2024/12/17 16:57
 */
public class AuthStorage {
    /**
     * 获取token信息
     */
    public static final String tokenKey = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJleHAiOjE3MzQ1MTExMTYsImF1ZCI6IndlYiIsInN1YiI6IjEiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE3MzQ0MjQ3MTYsInVzZXJJZCI6IjEifQ.lHh2uNrOr18b_9RTNv3noTHz1UrKtOUS971TQXEEEx0";
    /**
     * 模拟session
     */
    private static final HashMap<String, JwtUser> jwtUsers = new HashMap<>(100);

    /**
     * 获取全局用户信息
     *
     * @return
     */
    public static JwtUser getUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        // token 存放在请求头中，在柘林可以拿到用户的token
        return jwtUsers.get(request.getHeader("tokenKey"));
    }

    /**
     * 保存用户信息
     *
     * @param tokenKey
     * @param jwtUser
     */
    public static void setUser(String tokenKey, JwtUser jwtUser) {
        // 在session 中添加token
        jwtUsers.put(tokenKey, jwtUser);
    }

    /**
     * 移除token
     */
    public static void removeUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        jwtUsers.remove(request.getHeader("tokenKey"));
    }
}
